//
//  AssetManager.m
//  FileLockerPro
//
//  Created by SDSL-3 on 7/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AssetManager.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AssetsLibrary/ALAssetsLibrary.h>

@implementation AssetManager

- (id)init {
    self = [super init];
    if (self) {
        NSString *libpath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        root_dir    =   [libpath stringByAppendingPathComponent:ROOT_DIR];
        image_dir   =   [root_dir stringByAppendingPathComponent:IMAGE_DIR];
        video_dir   =   [root_dir stringByAppendingPathComponent:VIDEO_DIR];
        note_dir    =   [root_dir stringByAppendingPathComponent:NOTE_DIR];        
        
        
        [self createBaseDirsIsNotExist];
    }
    return self;
}

- (void)dealloc {
    
    [super dealloc];
}

-(NSString *)imagePathFromName:(NSString *)name{
    return [image_dir stringByAppendingPathComponent:name];
}

-(NSString *)videoPathFromName:(NSString *)name{
    return [video_dir stringByAppendingPathComponent:name];
}

-(NSString *)notePathFromName:(NSString *)name{
    return [note_dir stringByAppendingPathComponent:name];
}

-(void)createBaseDirsIsNotExist{
    NSFileManager *fm = [NSFileManager defaultManager];
    
    if(![fm fileExistsAtPath:root_dir]){
        [fm createDirectoryAtPath:root_dir withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    if(![fm fileExistsAtPath:image_dir]){
        [fm createDirectoryAtPath:image_dir withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    if(![fm fileExistsAtPath:video_dir]){
        [fm createDirectoryAtPath:video_dir withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    if(![fm fileExistsAtPath:note_dir]){
        [fm createDirectoryAtPath:note_dir withIntermediateDirectories:YES attributes:nil error:NULL];
    }
}

-(BOOL)fileExistsInPath:(NSString *)path{
    NSFileManager *fm = [NSFileManager defaultManager];
    return [fm fileExistsAtPath:path];
}

-(NSArray *)getAllFileNamesInDirectory:(NSString *)dirpath{
    NSFileManager *fm = [NSFileManager defaultManager];
    return [fm contentsOfDirectoryAtPath:dirpath error:NULL];
}

-(BOOL)saveNoteContents:(NSString *)contents WithName:(NSString *)name{
    NSFileManager *fm = [NSFileManager defaultManager];
    
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"dd MMM, yyyy"];
    
    NSString *dateString = [format stringFromDate:[NSDate date]];
    [format release];
    
    [fm createFileAtPath:[self notePathFromName:[NSString stringWithFormat:@"%@___-%@",name, dateString]] contents:[contents dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
    return YES;
}

-(NSString *)getNoteContents:(NSString *)name{
    NSFileManager *fm = [NSFileManager defaultManager];
    return  [[[NSString alloc] initWithData:[fm contentsAtPath:[self notePathFromName:name]] encoding:NSUTF8StringEncoding] autorelease];
}

-(NSArray *)getAllNotes{
    return [self getAllFileNamesInDirectory:note_dir];
}

-(BOOL)noteExists:(NSString *)name{
    return [self fileExistsInPath:[self notePathFromName:name]];
}

-(BOOL)deleteNote:(NSString *)name{
    return [self deleteFile:[self notePathFromName:name]];
}



-(BOOL)saveImage:(UIImage *)image WithName:(NSString *)name{
    [UIImageJPEGRepresentation(image, 10) writeToFile:[self imagePathFromName:name] options:NSDataWritingAtomic error:NULL];
    return YES;
}

-(BOOL)exportImage:(NSString *)name{
    NSString *path = [self imagePathFromName:name]; 
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    return YES;
}

-(NSArray *)getAllImages{
    return [self getAllFileNamesInDirectory:image_dir];
}

-(NSMutableArray *)getAllImagePaths{
    NSArray *names = [self getAllImages];
    NSMutableArray *paths = [[NSMutableArray alloc] init];
    if(names != nil){
        for (int i=0; i<[names count]; i++) {
            [paths addObject:[self imagePathFromName:[names objectAtIndex:i]]];
        }        
    }
    return [paths autorelease];
}


-(BOOL)deleteImage:(NSString *)name{
    return [self deleteFile:[self imagePathFromName:name]];
}


-(BOOL)deleteFile:(NSString *)path{
    NSFileManager *fm = [NSFileManager defaultManager];
    [fm removeItemAtPath:path error:NULL];
    return YES;
}


-(BOOL)saveVideo:(NSURL *)srcurl WithName:(NSString *)name{
    NSFileManager *fm = [NSFileManager defaultManager];
    [fm copyItemAtPath:[srcurl path] toPath:[self videoPathFromName:name] error:NULL];
    
    MPMoviePlayerController *mp = [[MPMoviePlayerController alloc] 
                                   initWithContentURL:srcurl];
    mp.shouldAutoplay = NO;
    mp.initialPlaybackTime = 0.1;
    mp.currentPlaybackTime = 0.1;
    // get the thumbnail
    UIImage *thumbnail = [mp thumbnailImageAtTime:0.1 
                                       timeOption:MPMovieTimeOptionNearestKeyFrame];
    // clean up the movie player
    [mp stop];
    [mp release];
    
    NSString *thumbpath = [NSString stringWithFormat:@"%@.jpg", [self videoPathFromName:name]];
    [UIImageJPEGRepresentation(thumbnail, 5) writeToFile:thumbpath atomically:YES];
    
    return YES;
}

-(BOOL)exportVideo:(NSString *)name{
    NSString *path = [self imagePathFromName:name]; 
    NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
    ALAssetsLibrary *al = [[ALAssetsLibrary alloc] init];
    [al writeVideoAtPathToSavedPhotosAlbum:url completionBlock:^(NSURL *assetURL, NSError *error){
        NSLog(@"%@", [error description]);
    }];
    
    [url release];
    [al release];
    return YES;
}

-(NSArray *)getAllVideos{
    return [self getAllFileNamesInDirectory:video_dir];
}

-(NSMutableArray *)getAllVideoPaths{
    NSArray *names = [self getAllVideos];
    NSMutableArray *paths = [[NSMutableArray alloc] init];
    if(names != nil){
        for (int i=0; i<[names count]; i++) {
            if ([[[names objectAtIndex:i] pathExtension] isEqualToString:@"jpg"]){
                continue;
            }
            
            
            [paths addObject:[self videoPathFromName:[names objectAtIndex:i]]];
        }        
    }
    return [paths autorelease];
}

-(BOOL)deleteVideo:(NSString *)name{
    NSString *thumbpath = [NSString stringWithFormat:@"%@.jpg", [self videoPathFromName:name]];
    [self deleteFile:thumbpath];
    return [self deleteFile:[self videoPathFromName:name]];
}

@end
